package Thread.New.带返回值的线程创建.线程工具;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrier_Use {
    public static void main(String[] args) {
        //拦截2个子线程屏障
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
        System.out.println("主线程开始执行");
        SubThread subThread1 = new SubThread(cyclicBarrier);
        SubThread subThread2 = new SubThread(cyclicBarrier);
        subThread1.start();
        subThread2.start();
    }

    static class SubThread extends Thread {
        private CyclicBarrier cyclicBarrier;
        public SubThread(CyclicBarrier cyclicBarrier){
            this.cyclicBarrier = cyclicBarrier;
        }
        @Override
        public void run() {
            try {
                System.out.println(getName() + " 线程开始执行任务");
                //模拟子线程执行第一个任务
                sleep(3000);
                System.out.println(getName() + " 线程任务完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            try {
                //完成第一个任务，告知达到屏障
                System.out.println("任务完成,进入等待");
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }


            //所有子线程都完成第一个任务后，继续运行每个子线程的下一个任务
            System.out.println(getName() + " 等待结束,继续执行");
        }
    }
}
